"""
数据库模块
"""

from sqlalchemy import create_engine, Column, Integer, String, Text, DateTime, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime

from .config import get_settings

settings = get_settings()

# 创建数据库引擎
engine = create_engine(
    settings.DATABASE_URL,
    connect_args={"check_same_thread": False} if "sqlite" in settings.DATABASE_URL else {}
)

# 创建会话工厂
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 创建基础模型类
Base = declarative_base()


class HotTrend(Base):
    """热点趋势模型"""
    __tablename__ = "hot_trends"
    
    id = Column(Integer, primary_key=True, index=True)
    title = Column(String(500), nullable=False)
    description = Column(Text)
    source = Column(String(50), nullable=False)  # weibo, zhihu, baidu
    rank = Column(Integer)
    heat_score = Column(Integer)
    url = Column(String(1000))
    created_at = Column(DateTime, default=datetime.utcnow)
    processed = Column(Boolean, default=False)


class GeneratedContent(Base):
    """生成的内容模型"""
    __tablename__ = "generated_contents"
    
    id = Column(Integer, primary_key=True, index=True)
    trend_id = Column(Integer, nullable=False)
    platform = Column(String(50), nullable=False)  # weibo, twitter, wechat
    content = Column(Text, nullable=False)
    hashtags = Column(String(500))
    status = Column(String(20), default="pending")  # pending, approved, published, failed
    created_at = Column(DateTime, default=datetime.utcnow)
    published_at = Column(DateTime)


class PublishRecord(Base):
    """发布记录模型"""
    __tablename__ = "publish_records"
    
    id = Column(Integer, primary_key=True, index=True)
    content_id = Column(Integer, nullable=False)
    platform = Column(String(50), nullable=False)
    platform_post_id = Column(String(100))
    status = Column(String(20), nullable=False)  # success, failed, retry
    error_message = Column(Text)
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow)


class ScheduledTask(Base):
    """定时任务模型"""
    __tablename__ = "scheduled_tasks"
    
    id = Column(Integer, primary_key=True, index=True)
    task_name = Column(String(100), nullable=False)
    task_type = Column(String(50), nullable=False)  # scrape, generate, publish
    parameters = Column(Text)  # JSON格式的参数
    schedule = Column(String(100))  # cron表达式
    enabled = Column(Boolean, default=True)
    last_run = Column(DateTime)
    next_run = Column(DateTime)
    created_at = Column(DateTime, default=datetime.utcnow)


def init_db():
    """初始化数据库"""
    Base.metadata.create_all(bind=engine)


def get_db():
    """获取数据库会话"""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()